<template>
  <div class="flex flex-col h-full w-full bg-white">
    <!-- 顶部标题 -->
    <header class="flex items-center justify-between p-4 border-b">
      <h1 class="text-2xl font-bold text-gray-800">智能对话系统</h1>
      <div class="flex space-x-3">
        <button 
          @click="toggleHistory" 
          class="text-sm text-black hover:text-black hover:no-underline p-1 focus:outline-none focus:ring-0" style="background: none; border: none; cursor: pointer;"
          title="查看历史记录"
        >
          历史记录
        </button>
        <button 
          @click="showSidebars = false; selectedUser = null; messages = []" 
          class="text-sm text-black hover:text-black hover:no-underline p-1 focus:outline-none focus:ring-0" style="background: none; border: none; cursor: pointer;"
          title="退出聊天"
        >
          退出聊天
        </button>
          <button 
            v-if="showHistory && historyRecords.length > 0"
            @click="clearAllHistory"
            class="text-sm text-red-500 hover:text-red-600 hover:no-underline p-1 focus:outline-none focus:ring-0 mx-auto block"
            style="background: none; border: none; cursor: pointer;"
            title="清空所有历史记录"
          >
            清空
          </button>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="flex flex-1 overflow-hidden w-full">
      <!-- 左侧面板 -->
      <aside :class="['transition-all duration-700 ease-out transform', showSidebars ? 'w-64 translate-x-0' : 'w-0 -translate-x-full', 'border-r bg-white p-4 flex-shrink-0 overflow-hidden']">
        <!-- 搜索框 -->
        <div class="mb-4 relative">
          <div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
            <i class="fa fa-search text-gray-400"></i>
          </div>
          <input 
            type="text" 
            placeholder="搜索角色..." 
            class="w-full pl-10 pr-4 py-2.5 border border-gray-200 rounded-lg text-sm focus:outline-none shadow-md focus:shadow-lg transition-all duration-300 bg-white"
          />
        </div>
        
        <!-- 角色列表 -->
        <div class="space-y-2 overflow-y-auto" style="max-height: calc(100vh - 150px);">
          <div 
            v-for="user in roleList" 
            :key="user.id" 
            @click="selectUser(user)"
            class="flex items-center p-2 rounded-lg cursor-pointer hover:bg-gray-50"
          >
            <div 
              class="w-8 h-8 rounded-full flex items-center justify-center mr-3" 
              :style="{ backgroundColor: user.avatarColor }"
            >
              <span :style="{ color: this.getTextColor(user.avatarColor) }" class="text-sm">{{ user.name.charAt(0) }}</span>
            </div>
            <div>
              <div class="text-sm font-medium text-gray-800">{{ user.name }}</div>
              <div class="text-xs text-gray-600">{{ user.title }}</div>
            </div>
          </div>
        </div>
      </aside>

      <!-- 中间聊天区域 -->
      <section class="flex-1 flex flex-col bg-gray-50 overflow-hidden">
        <!-- 历史记录面板 -->
        <transition name="history-panel">
          <div v-if="showHistory" class="absolute inset-0 bg-white z-10 p-6 overflow-y-auto">
            <div class="flex items-center justify-between mb-4">
              <h2 class="text-xl font-bold history-title">对话历史记录</h2>
              <button 
                  @click="toggleHistory"
                  class="text-black hover:text-black hover:no-underline p-1 focus:outline-none focus:ring-0" style="background: none; border: none; cursor: pointer;"
                  title="关闭历史记录"
                >
                  关闭
                </button>
            </div>
            <div v-if="historyRecords.length === 0" class="text-center text-gray-500 py-10">
              <p>暂无历史记录</p>
            </div>
            <div v-else class="space-y-3">
              <div 
                v-for="record in historyRecords" 
                :key="record.roleId"
                @click="loadFromHistory(record)"
                class="p-1 cursor-pointer flex items-center justify-between text-black"
              >
                <div class="flex items-center">
                  <div 
                    class="w-8 h-8 rounded-full flex items-center justify-center mr-3" 
                    :style="{ backgroundColor: record.roleColor }"
                  >
                    <span :style="{ color: this.getTextColor(record.roleColor) }" class="text-sm">{{ record.roleName.charAt(0) }}</span>
                  </div>
                  <div class="flex-1 min-w-0">
                    <div class="text-sm font-medium text-gray-800">{{ record.roleName }}</div>
                    <div class="text-xs text-gray-500 truncate">{{ record.lastMessage }}</div>
                    <div class="flex items-center justify-between mt-1">
                      <span class="text-xs text-gray-400">{{ record.lastMessageTime }}</span>
                      <span class="text-xs text-gray-400">{{ record.messageCount }}条消息</span>
                    </div>
                  </div>
                </div>
                <button 
                  @click="clearHistory(record.roleId, $event)"
                  class="text-black hover:text-black hover:no-underline p-1 ml-2 focus:outline-none focus:ring-0" style="background: none; border: none; cursor: pointer;"
                  title="清除此角色的历史记录"
                >
                  删除
                </button>
              </div>
            </div>
            <div class="mt-6 text-center">
              <button 
                @click="clearAllHistory"
                class="text-sm text-red-500 hover:text-red-600 hover:no-underline p-1 focus:outline-none focus:ring-0"
                style="background: none; border: none; cursor: pointer;"
                title="清空所有历史记录"
              >
                清除所有历史记录
              </button>
            </div>
          </div>
        </transition>
        
        <div class="flex-1 overflow-y-auto p-6" id="chatMessages">
          <div v-if="!selectedUser && !showHistory" class="flex flex-col items-center justify-center h-full">
            <div @click="toggleSidebars" class="relative mb-6 p-6 cursor-pointer bg-gradient-to-br from-white to-gray-50 rounded-xl shadow-lg border border-gray-100 transform transition-all duration-300 hover:shadow-xl hover:scale-105 w-full max-w-md mx-auto">
            <img src="/img/robot.png" alt="智能机器人" class="w-40 h-40 rotate-animation mx-auto" :class="{ 'jump-animation': isJumping }" />
          </div>
            <h2 class="text-2xl font-bold mb-2">{{ getGreeting() }}</h2>
            <p class="text-gray-500 text-sm text-center">点击它开始对话</p>
          </div>
          
          <div v-else>
            <div v-if="messages.length === 0" class="flex flex-col items-center justify-center h-full text-gray-500">
              <p class="text-lg">现在可以进行对话了</p>
            </div>
            <div v-else>
              <div v-for="message in messages" :key="message.id" class="flex items-start mb-4" :class="{ 'justify-end': message.isUser }">
                <div v-if="!message.isUser" class="w-8 h-8 rounded-full mr-2 flex items-center justify-center" :style="{ backgroundColor: selectedUser.avatarColor }">
                  <span :style="{ color: this.getTextColor(selectedUser.avatarColor) }" class="text-xs">{{ selectedUser.name.charAt(0) }}</span>
                </div>
                <div class="max-w-md">
                    <div 
                      :class="['p-3 rounded-lg flex items-center', message.isUser ? 'bg-blue-500 text-white' : 'bg-white text-gray-800']"
                    >
                      {{ message.content }}
                      <span 
                        v-if="message.isVoice && message.audioUrl"
                        class="ml-2 p-1 cursor-pointer" 
                        @click="playMessageAudio(message)"
                        title="播放语音"
                        :style="{
                          color: message.isUser ? 'white' : '#4A90E2',
                          display: 'inline-block',
                          padding: '4px',
                          cursor: 'pointer',
                          userSelect: 'none'
                        }"
                      >
                        <i class="fa fa-volume-up"></i>
                      </span>
                    </div>
                    <span class="text-xs text-gray-400 mt-1 block" :class="{ 'text-right': message.isUser }">
                      {{ message.time }}
                    </span>
                </div>
                <div v-if="message.isUser" class="w-8 h-8 rounded-full ml-2 flex items-center justify-center" :style="{ backgroundColor: userAvatarColor }">
                  <span :style="{ color: this.getTextColor(userAvatarColor) }" class="text-xs">用户</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div v-if="!showHistory" class="border-t bg-white">
          <!-- 语音设置面板 -->
          <transition name="fade">
            <div v-if="showVoiceSettings" class="p-4 border-b bg-gray-50">
              <div class="flex flex-col space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">语速调节</label>
                    <div class="flex items-center space-x-2">
                      <i class="fa fa-tachometer text-gray-500"></i>
                      <input 
                        type="range" 
                        min="0.5" 
                        max="2.0" 
                        step="0.1" 
                        v-model.number="voiceSettings.speed" 
                        class="slider w-full h-2 bg-gray-200 rounded-lg appearance-none outline-none" 
                        @input="updateSliderBackground"
                        ref="speedSlider"
                      >
                      <span class="text-sm font-medium text-gray-800 min-w-[35px] text-right">{{ voiceSettings.speed.toFixed(1) }}x</span>
                    </div>
                  </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">语音风格</label>
                  <select v-model="voiceSettings.style" class="w-full p-2 border border-gray-300 rounded-md text-gray-800 bg-white">
                    <option value="default">默认</option>
                    <option value="young">年轻活力</option>
                    <option value="wise">成熟稳重</option>
                    <option value="poetic">诗意优雅</option>
                    <option value="knowledgeable">知识渊博</option>
                  </select>
                </div>
              </div>
            </div>
          </transition>
          <div class="p-4 transition-all duration-700 ease-out" v-show="showSidebars">
            <div class="flex items-center space-x-3">
            <button class="p-2 text-white rounded-full hover:bg-gray-700 transition-colors" @click="toggleVoiceMode" data-voice-toggle>
              <i class="fa fa-microphone"></i>
            </button>
            <button class="p-2 text-white rounded-full hover:bg-gray-700 transition-colors" @click="showVoiceSettings = !showVoiceSettings">
              <i class="fa fa-sliders"></i>
            </button>
            
            <div class="flex-1">
              <textarea
                  v-model="inputMessage"
                  :placeholder="isRecognizingVoice ? '正在识别语音...' : '输入消息'"
                  class="w-full p-3 border border-gray-200 rounded-lg text-sm bg-white shadow-sm focus:shadow-md focus:border-blue-300 transition-all duration-300"
                  rows="1"
                  @keydown.enter.prevent="sendMessage"
              ></textarea>
              
              <!-- 语音录制组件 -->
              <VoiceRecorder
                v-if="isVoiceMode"
                @recording-status-change="onRecordingStatusChange"
                @recognition-result="handleRecognitionResult"
              />
            </div>
            
            <button class="p-3 bg-blue-500 text-white rounded-full hover:bg-blue-600 transition-colors" @click="sendMessage">
              <i class="fa fa-paper-plane"></i>
            </button>
          </div>
          </div>
        </div>
      </section>

      </main>
  </div>
</template>

<script>
import VoiceRecorder from './VoiceRecorder.vue';
import { audioUtils, chatSession, calculateTextColor } from '../utils/index.js';
import { getCharacterList, getCharacterDetail, sendMessage, checkBackendConnection, transcribeAudio, chatAdd } from '../api/roleApi.js';

export default {
  name: 'MainLayout',
  components: {
    VoiceRecorder
  },
  
  data() {
      return {
      selectedUser: null,
      inputMessage: '',
      messages: [],
      userAvatarColor: '#4A90E2',
      isJumping: false,
      isVoiceMode: false,
      isRecognizingVoice: false,
      isPlayingAudio: false,
      showHistory: false,
      historyRecords: [],
      useBackendAPI: true, // 默认使用后端API
        showSidebars: false, // 控制侧边栏的显示状态
        lastVoiceMessageIndex: null, // 语音消息在列表中的索引（用于实时更新）
      // 语音设置
      voiceSettings: {
        speed: 1.0, // 语速，范围0.5-2.0
        style: 'default' // 语音风格: default, young, wise, poetic, knowledgeable
      },
      showVoiceSettings: false, // 是否显示语音设置面板
      apiBaseUrl: '/api', // 后端API基础URL
      roleList: [
        {
          id: 1,
          name: '李白',
          title: '诗仙',
          avatarColor: '#FF6B6B'
        },
        {
          id: 2,
          name: '爱因斯坦',
          title: '物理学家',
          avatarColor: '#4ECDC4'
        },
        {
          id: 3,
          name: '拿破仑',
          title: '军事家、政治家',
          avatarColor: '#45B7D1'
        },
        {
          id: 4,
          name: '居里夫人',
          title: '物理学家、化学家',
          avatarColor: '#96CEB4'
        },
        {
          id: 5,
          name: '爱迪生',
          title: '发明家、科学家',
          avatarColor: '#FFEAA7'
        },
        {
          id: 6,
          name: '莎士比亚',
          title: '文学家、戏剧家',
          avatarColor: '#DDA0DD'
        },
        {
          id: 7,
          name: '达芬奇',
          title: '艺术家、科学家',
          avatarColor: '#98D8C8'
        },
        {
          id: 8,
          name: '牛顿',
          title: '物理学家、数学家',
          avatarColor: '#F7DC6F'
        }
      ]
    };
  },
  
  mounted() {
      // 组件挂载时加载历史记录
      this.loadUserHistory();
      
      // 添加键盘事件监听，支持ESC关闭历史记录面板
      document.addEventListener('keydown', this.handleKeydown);
      
      // 添加全局点击事件监听，实现点击空白处取消语音模式
      document.addEventListener('click', this.handleGlobalClick);
      
      // 初始化滑块样式
      this.$nextTick(() => {
        this.updateSliderBackground();
      });
      
      // 添加全局样式
      const style = document.createElement('style');
      style.textContent = `
        .slider {
          -webkit-appearance: none;
          height: 6px;
        }
        .slider::-webkit-slider-thumb {
          -webkit-appearance: none;
          appearance: none;
          width: 18px;
          height: 18px;
          border-radius: 50%;
          background: #4A90E2;
          cursor: pointer;
          border: 2px solid white;
          box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        .slider::-moz-range-thumb {
          width: 18px;
          height: 18px;
          border-radius: 50%;
          background: #4A90E2;
          cursor: pointer;
          border: 2px solid white;
          box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        // 完全去除音频按钮的所有默认样式
        .audio-button,
        .audio-button:hover,
        .audio-button:focus,
        .audio-button:active {
          background: transparent !important;
          border: none !important;
          outline: none !important;
          box-shadow: none !important;
          -webkit-tap-highlight-color: transparent !important;
        }
        .audio-button:focus {
          outline: none !important;
          box-shadow: none !important;
        }
      `;
      document.head.appendChild(style);
      this._sliderStyle = style;
  },
  
  beforeUnmount() {
      // 组件卸载时移除事件监听
      document.removeEventListener('keydown', this.handleKeydown);
      document.removeEventListener('click', this.handleGlobalClick);
      // 移除全局样式
      if (this._sliderStyle && document.head.contains(this._sliderStyle)) {
        document.head.removeChild(this._sliderStyle);
      }
    },
    
    methods: {
      // 根据时间获取智能问好
      getGreeting() {
        const now = new Date();
        const hour = now.getHours();
        let greetings = [];
        
        // 根据时间设置不同的问候语列表
        if (hour >= 5 && hour < 12) {
          greetings = [
            '早上好！',
            '新的一天开始了！',
            '早晨好！',
            '早安，祝你有美好的一天！',
            '早上好，今天过得怎么样？',
            '早安，很高兴见到你！'
          ];
        } else if (hour >= 12 && hour < 18) {
          greetings = [
            '下午好！',
            '午后好！',
            '下午愉快！',
            '下午好，有什么可以帮助你的吗？',
            '下午好，今天顺利吗？',
            '下午好，很高兴为你服务！'
          ];
        } else {
          greetings = [
            '晚上好！',
            '夜间好！',
            '晚上好，今天过得怎么样？',
            '晚安，需要什么帮助吗？',
            '晚上好，很高兴见到你！',
            '晚上好，祝你愉快！'
          ];
        }
        
        // 随机选择一条问候语
        return greetings[Math.floor(Math.random() * greetings.length)];
      },
      
      // 切换侧边栏显示状态
      toggleSidebars() {
        this.showSidebars = !this.showSidebars;
        this.jumpAnimation();
      },
      
      // 更新滑块背景渐变
      updateSliderBackground() {
        if (this.$refs.speedSlider) {
          const slider = this.$refs.speedSlider;
          const value = this.voiceSettings.speed;
          const percent = ((value - 0.5) * 100) / 1.5;
          slider.style.background = `linear-gradient(to right, #4A90E2 0%, #4A90E2 ${percent}%, #E5E7EB ${percent}%, #E5E7EB 100%)`;
        }
      },
      
      // 选择用户
      selectUser(user) {
      this.selectedUser = user;
      this.messages = [];
      // 加载用户的历史对话记录
      this.loadUserHistory(user.id);
    },
    
    // 获取角色描述
    getRoleDescription(roleName) {
      const descriptions = {
        '李白': '唐代著名浪漫主义诗人，被后人誉为"诗仙"，其诗歌风格豪放飘逸，意境奇妙。',
        '爱因斯坦': '20世纪最伟大的物理学家之一，相对论的创立者，对现代物理学产生了深远影响。',
        '拿破仑': '法国军事和政治领袖，法兰西第一帝国的缔造者，军事才能卓越。',
        '居里夫人': '首位获得诺贝尔奖的女性科学家，发现了镭和钋元素，对放射性研究做出了巨大贡献。',
        '爱迪生': '美国著名发明家，拥有1000多项专利，其中包括电灯、留声机等改变人类生活的发明。',
        '莎士比亚': '英国文艺复兴时期伟大的戏剧家和诗人，作品对世界文学产生了深远影响。',
        '达芬奇': '意大利文艺复兴时期的艺术家、科学家、发明家，代表作有《蒙娜丽莎》等。',
        '牛顿': '英国著名物理学家和数学家，万有引力定律的发现者，经典力学体系的建立者。'
      };
      
      return descriptions[roleName] || '这是一位有趣的角色，快来和他对话吧！';
    },
    
    // 获取快速对话内容
    getQuickMessages(roleName) {
      const quickMessages = {
        '李白': [
          '能为我作一首诗吗？',
          '你最喜欢自己的哪首作品？',
          '你的诗歌创作灵感来自哪里？'
        ],
        '爱因斯坦': [
          '什么是相对论？',
          '你认为科学的未来发展方向是什么？',
          '你如何看待时间和空间的关系？'
        ],
        '拿破仑': [
          '你最著名的战役是哪一场？',
          '作为领导者，你认为最重要的品质是什么？',
          '你对历史有什么看法？'
        ],
        '居里夫人': [
          '你发现镭元素的过程是怎样的？',
          '作为女性科学家，你遇到过哪些挑战？',
          '你对科学研究有什么建议？'
        ],
        '爱迪生': [
          '你发明电灯的过程中遇到了哪些困难？',
          '你认为哪个发明对人类影响最大？',
          '你对创新有什么看法？'
        ],
        '莎士比亚': [
          '你最著名的作品是什么？',
          '你的创作灵感来自哪里？',
          '你如何看待人性？'
        ],
        '达芬奇': [
          '你是如何在艺术和科学领域都取得成就的？',
          '《蒙娜丽莎》这幅画有什么特别之处？',
          '你的哪些发明构想在当时是超前的？'
        ],
        '牛顿': [
          '苹果落地的故事是真的吗？',
          '万有引力定律是如何发现的？',
          '你如何看待科学与宗教的关系？'
        ]
      };
      
      return quickMessages[roleName] || [
        '你好，很高兴认识你！',
        '能介绍一下你自己吗？',
        '今天天气真好！'
      ];
    },
    
    // 发送消息
    sendMessage() {
      // 参数校验：必须选择角色并且有有效输入
      if (!this.selectedUser) {
        alert('请先选择一个角色');
        return;
      }
      if (!this.inputMessage || !this.inputMessage.trim()) {
        alert('请输入消息内容');
        return;
      }
      
      const userMessage = {
        id: Date.now(),
        content: this.inputMessage.trim(),
        time: this.formatTime(new Date()),
        isUser: true
      };
      
      this.messages.push(userMessage);
      this.inputMessage = '';
      
      // 保存到历史记录
      this.saveUserHistory();
      
      // 滚动到底部
      this.scrollToBottom();
      
      // 根据用户选择决定使用后端API（流式）还是模拟回复
      if (this.useBackendAPI) {
        this.getBackendResponseStreaming(userMessage.content);
      } else {
        this.getMockResponse(userMessage.content);
      }
    },
    
    // 发送快速消息
    sendQuickMessage(message) {
      if (!this.selectedUser) return;
      
      const userMessage = {
        id: Date.now(),
        content: message,
        time: this.formatTime(new Date()),
        isUser: true
      };
      
      this.messages.push(userMessage);
      
      // 保存到历史记录
      this.saveUserHistory();
      
      // 滚动到底部
      this.scrollToBottom();
      
      // 根据用户选择决定使用后端API还是模拟回复
      if (this.useBackendAPI) {
        this.getBackendResponse(message);
      } else {
        this.getMockResponse(message);
      }
    },
    
    // 获取后端API回复
    // 使用 GET /chat/add 流式返回内容
    async getBackendResponseStreaming(message) {
      try {
        // 获取或创建保持一致的 chatId（同一角色）
        const chatId = chatSession.ensure(this.selectedUser.id);

        // 先创建一个占位的机器人消息，用于逐步填充流式内容
        const botMessage = {
          id: Date.now() + 1,
          content: '',
          time: this.formatTime(new Date()),
          isUser: false,
          contentType: 'TEXT',
          audioUrl: null
        };
        this.messages.push(botMessage);

        // 调用符合后端规范的聊天接口（流式）
        const roleName = this.selectedUser?.name || undefined;
        const result = await chatAdd({
          role: roleName,
          prompt: message,
          chatId,
          onChunk: (chunk) => {
            // 逐步填充内容并滚动到底部
            botMessage.content += chunk;
            this.scrollToBottom();
          }
        });

        // 如果返回了聚合内容，确保最终一致
        if (result && result.code === 200) {
          // 最终时间戳更新为完成时间
          botMessage.time = this.formatTime(new Date());
        } else {
          throw new Error('API返回了无效数据');
        }
        
        // 保存到历史记录
        this.saveUserHistory();
        
        // 滚动到底部
        this.scrollToBottom();
      } catch (error) {
        console.error('获取回复失败:', error);
        // 显示错误消息
        this.messages.push({
          id: Date.now() + 1,
          content: '抱歉，我暂时无法回复。请稍后再试。',
          time: this.formatTime(new Date()),
          isUser: false
        });
      }
    },
    
    // 获取模拟回复
    getMockResponse(message) {
      // 模拟思考延迟
      setTimeout(() => {
        const botResponse = {
          id: Date.now() + 1,
          content: this.generateMockResponse(message),
          time: this.formatTime(new Date()),
          isUser: false
        };
        
        this.messages.push(botResponse);
        
        // 保存到历史记录
        this.saveUserHistory();
        
        // 滚动到底部
        this.scrollToBottom();
      }, 1000);
    },
    
    // 生成模拟回复
    generateMockResponse(message) {
      const responses = {
        '李白': [
          '天生我材必有用，千金散尽还复来。',
          '人生得意须尽欢，莫使金樽空对月。',
          '长风破浪会有时，直挂云帆济沧海。'
        ],
        '爱因斯坦': [
          '想象力比知识更重要。',
          '时间是一种错觉。',
          '上帝不会掷骰子。'
        ],
        '拿破仑': [
          '不想当将军的士兵不是好士兵。',
          '胜利属于最坚韧的人。',
          '在我的字典里，没有不可能这个词。'
        ],
        '居里夫人': [
          '科学需要人的全部生命。',
          '弱者等待时机，强者创造时机。',
          '荣誉使我变得越来越愚蠢。'
        ],
        '爱迪生': [
          '天才是1%的灵感加上99%的汗水。',
          '我没有失败，我只是找到了10000种不奏效的方法。',
          '机遇总是垂青于有准备的人。'
        ],
        '莎士比亚': [
          '生存还是毁灭，这是一个问题。',
          '真爱无坦途。',
          '一千个人眼中有一千个哈姆雷特。'
        ],
        '达芬奇': [
          '学习永无止境。',
          '简单是复杂的终极形式。',
          '细节决定成败。'
        ],
        '牛顿': [
          '如果说我看得比别人更远些，那是因为我站在巨人的肩膀上。',
          '万有引力是宇宙间最神秘的力量。',
          '我不知道世人怎么看我，但我自己觉得我不过是一个在海边玩耍的孩子。'
        ]
      };
      
      const roleResponses = responses[this.selectedUser.name] || [
        '感谢你的消息！',
        '我很乐意与你交流。',
        '这个问题很有趣！'
      ];
      
      return roleResponses[Math.floor(Math.random() * roleResponses.length)];
    },
    
    // 播放录制的语音消息
    playMessageAudio(message) {
      if (this.isPlayingAudio || !message.isVoice || !message.audioUrl) return;
      
      this.isPlayingAudio = true;
      
      // 创建音频元素播放录音
      const audio = new Audio(message.audioUrl);
      
      audio.onended = () => {
        this.isPlayingAudio = false;
      };
      
      audio.onerror = (error) => {
        console.error('语音播放失败:', error);
        this.isPlayingAudio = false;
      };
      
      // 开始播放
      audio.play().catch(error => {
        console.error('无法播放语音:', error);
        this.isPlayingAudio = false;
      });
    },
    
    // 播放消息语音（文字转语音）
    playMessageAsAudio(message) {
      if (this.isPlayingAudio || message.isVoice) return;
      
      this.isPlayingAudio = true;
      
      // 调用文字转语音函数
      const textToSpeech = (text) => {
        const utterance = new SpeechSynthesisUtterance(text);
        utterance.lang = 'zh-CN';
        
        // 使用语音设置中的语速
        utterance.rate = this.voiceSettings.speed;
        
        // 根据风格设置调整语音参数
        switch (this.voiceSettings.style) {
          case 'young':
            utterance.pitch = 1.3;
            utterance.rate = Math.min(this.voiceSettings.speed * 1.1, 2.0);
            break;
          case 'wise':
            utterance.pitch = 0.9;
            utterance.rate = Math.max(this.voiceSettings.speed * 0.8, 0.5);
            break;
          case 'poetic':
            utterance.pitch = 1.2;
            utterance.rate = Math.max(this.voiceSettings.speed * 0.9, 0.6);
            break;
          case 'knowledgeable':
            utterance.pitch = 1.0;
            utterance.rate = Math.max(this.voiceSettings.speed * 0.95, 0.7);
            break;
          default:
            // default 风格使用标准设置
            break;
        }
        
        utterance.onend = () => {
          this.isPlayingAudio = false;
        };
        
        utterance.onerror = () => {
          this.isPlayingAudio = false;
        };
        
        speechSynthesis.speak(utterance);
      };
      
      textToSpeech(message.content);
    },
    
    // 切换语音模式
    toggleVoiceMode() {
      this.isVoiceMode = !this.isVoiceMode;
    },
    
    // 处理全局点击事件，实现点击空白处取消语音模式
    handleGlobalClick(event) {
      // 只有在语音模式下才需要处理
      if (!this.isVoiceMode) return;
      
      // 检查点击目标是否是语音录制相关元素
      const voiceRecorderElement = event.target.closest('.voice-recorder');
      
      // 检查点击目标是否是麦克风按钮或其内部元素
      const microphoneButton = event.target.closest('[data-voice-toggle]');
      
      // 如果点击的不是语音录制组件且不是麦克风按钮，则取消语音模式
      if (!voiceRecorderElement && !microphoneButton) {
        this.isVoiceMode = false;
      }
    },
    
    // 录音状态变化（开始/结束）
    onRecordingStatusChange(isRecording) {
      this.isRecognizingVoice = isRecording;
      if (isRecording) {
        // 在输入框中显示提示文本
        this.inputMessage = '正在识别语音...';
        // 若已选择角色，则在消息列表中插入一条占位语音消息
        if (this.selectedUser) {
          const userMessage = {
            id: Date.now(),
            content: '[正在识别语音...]',
            time: this.formatTime(new Date()),
            isUser: true,
            isVoice: true
          };
          this.lastVoiceMessageIndex = this.messages.length;
          this.messages.push(userMessage);
          this.scrollToBottom();
        }
      } else {
        // 结束识别后保持已识别文本在输入框中；若仍为占位提示则清空
        if (this.inputMessage === '正在识别语音...') {
          this.inputMessage = '';
        }
        if (this.lastVoiceMessageIndex !== null) {
          this.saveUserHistory();
        }
        this.isVoiceMode = false;
        this.lastVoiceMessageIndex = null;
      }
    },

    // 实时识别结果处理
    handleRecognitionResult(text) {
      const content = text || '';
      // 将识别文本实时显示在输入框
      this.inputMessage = content;
      // 若存在语音消息占位，则同步更新其内容
      if (this.lastVoiceMessageIndex !== null) {
        this.messages[this.lastVoiceMessageIndex].content = content;
      }
      this.scrollToBottom();
    },
    
    // 跳跃动画
    jumpAnimation() {
      this.isJumping = true;
      setTimeout(() => {
        this.isJumping = false;
      }, 500);
    },
    
    // 加载用户历史记录
    loadUserHistory(roleId = null) {
      if (roleId) {
        // 加载特定用户的历史消息
        const savedMessages = localStorage.getItem(`messages_${roleId}`);
        if (savedMessages) {
          this.messages = JSON.parse(savedMessages);
        }
      } else {
        // 加载所有历史记录列表
        const savedHistory = localStorage.getItem('history_records');
        if (savedHistory) {
          this.historyRecords = JSON.parse(savedHistory);
        }
      }
      
      // 滚动到底部
      this.scrollToBottom();
    },
    
    // 保存用户历史记录
    saveUserHistory() {
      if (!this.selectedUser) return;
      
      // 保存消息历史
      localStorage.setItem(`messages_${this.selectedUser.id}`, JSON.stringify(this.messages));
      
      // 更新历史记录列表
      const lastMessage = this.messages[this.messages.length - 1];
      if (lastMessage) {
        const existingIndex = this.historyRecords.findIndex(record => record.roleId === this.selectedUser.id);
        
        const historyRecord = {
          roleId: this.selectedUser.id,
          roleName: this.selectedUser.name,
          roleColor: this.selectedUser.avatarColor,
          lastMessage: lastMessage.content,
          lastMessageTime: lastMessage.time,
          messageCount: this.messages.filter(msg => !msg.isUser).length
        };
        
        if (existingIndex >= 0) {
          this.historyRecords[existingIndex] = historyRecord;
        } else {
          this.historyRecords.unshift(historyRecord);
        }
        
        // 保存历史记录列表
        localStorage.setItem('history_records', JSON.stringify(this.historyRecords));
      }
    },
    
    // 更新历史记录列表
    updateHistoryList() {
      this.loadUserHistory();
    },
    
    // 切换历史记录显示
    toggleHistory() {
      this.showHistory = !this.showHistory;
      // 如果打开历史记录，加载所有历史记录
      if (this.showHistory) {
        this.loadUserHistory();
      }
    },
    
    // 从历史记录中加载对话
    loadFromHistory(record) {
      // 查找对应的用户
      const user = this.roleList.find(u => u.id === record.roleId);
      if (user) {
        this.selectUser(user);
        this.toggleHistory();
      }
    },
    
    // 清除特定角色的历史记录
    clearHistory(roleId, event) {
      event.stopPropagation();
      
      if (confirm('确定要清除该角色的历史记录吗？')) {
        // 清除本地存储的消息历史
        localStorage.removeItem(`messages_${roleId}`);
        
        // 从历史记录列表中移除
        this.historyRecords = this.historyRecords.filter(record => record.roleId !== roleId);
        localStorage.setItem('history_records', JSON.stringify(this.historyRecords));
        
        // 如果当前选中的是该用户，清空消息
        if (this.selectedUser && this.selectedUser.id === roleId) {
          this.messages = [];
        }
      }
    },
    
    // 清除所有历史记录
    clearAllHistory() {
      if (confirm('确定要清除所有历史记录吗？')) {
        // 清除所有用户的消息历史
        this.roleList.forEach(user => {
          localStorage.removeItem(`messages_${user.id}`);
        });
        
        // 清空历史记录列表
        this.historyRecords = [];
        localStorage.removeItem('history_records');
        
        // 清空当前消息
        this.messages = [];
      }
    },
    
    // 处理键盘事件
    handleKeydown(event) {
      // ESC键关闭历史记录面板
      if (event.key === 'Escape' && this.showHistory) {
        this.toggleHistory();
      }
    },
    
    // 滚动到底部
    scrollToBottom() {
      setTimeout(() => {
        const chatMessages = document.getElementById('chatMessages');
        if (chatMessages) {
          chatMessages.scrollTop = chatMessages.scrollHeight;
        }
      }, 100);
    },
    
    // 格式化时间
    formatTime(date) {
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },
    
    // 根据背景色计算合适的文本颜色（黑或白）
    getTextColor(bgColor) {
      // 使用工具函数计算文本颜色
      return calculateTextColor(bgColor);
    }
  }
};
</script>

<style scoped>
/* 旋转动画 */
.rotate-animation {
  animation: rotate 10s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 跳跃动画 */
.jump-animation {
  animation: jump 0.5s ease-out;
}

@keyframes jump {
  0% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-30px);
  }
  100% {
    transform: translateY(0);
  }
}

/* 历史记录面板动画 */
.history-panel-enter-active,
.history-panel-leave-active {
  transition: all 0.3s ease;
}
.history-panel-enter-from {
  opacity: 0;
  transform: translateX(100%);
}
.history-panel-leave-to {
  opacity: 0;
  transform: translateX(100%);
}

/* 角色信息面板立体动画 */
.role-panel-enter-active {
  transition: all 0.4s ease-out;
}
.role-panel-leave-active {
  transition: all 0.3s ease-in;
}
.role-panel-enter-from {
  opacity: 0;
  transform: scale(0.95) translateY(20px);
  box-shadow: 0 0 0 rgba(0, 0, 0, 0.1);
}
.role-panel-leave-to {
  opacity: 0;
  transform: scale(0.95) translateY(-20px);
  box-shadow: 0 0 0 rgba(0, 0, 0, 0.1);
}
    /* 角色信息面板切换动画 */
    .role-info-panel {
      animation: fadeInUp 0.5s ease-out;
    }
    
    @keyframes fadeInUp {
      from {
        opacity: 0;
        transform: translateY(20px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }
</style>
